<template>
  <el-form ref="forma" :model="data" :validate-on-rule-change="false" :rules="validateRule" v-bind="$attrs">
    <slot></slot>

    <div style="display: none">
      <button type="submit"/>
    </div>
  </el-form>
</template>

<script>
export default {
  name: 'KForm',
  inheritAttrs: false,
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rules: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      tabIndex: 0,
      autorules: {}
    }
  },
  computed: {
    validateRule () {
      return {
        ...this.autorules,
        ...this.rules
      }
    }
  },
  created () {
    this.$root.$on('k-form-add-validate', (data) => {
      if (data.prop && data.validate && data.validate.length) {
        let tmps = []
        data.validate.map((rule) => {
          if (rule === 'required') {
            tmps.push({
              [rule]: true,
              message: `${data.label || data.prop}不能为空`
            })
          }
        })
        this.$set(this.autorules, data.prop, tmps)
      }
    })
  },
  mounted () {
    this.$nextTick(() => {
      this.$el.onsubmit = (evt) => {
        evt.preventDefault()
        this.onSubmit(evt)
      }
    })
  },
  methods: {
    onSubmit (evt) {
      if (this.validateRule && Object.keys(this.validateRule).length) {
        this.$refs['forma'].validate((check) => {
          if (check) {
            this.$emit('submit', evt)
          } else {
            this.$nextTick(() => {
              document.querySelector('.is-error').focus()
            })
            this.$emit('cancel', evt)
          }
        })
      } else {
        this.$emit('submit', evt)
      }
    },
    resetFields () {
      this.$refs['forma'].resetFields()
    },
    clearValidate () {
      this.$refs['forma'].clearValidate()
    }
  }
}
</script>

<style scoped>

</style>
